package com.ctrun.view.cateye.indicatorview.widget.banner;

import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ctrun on 2017/12/14.
 */

public abstract class LoopAdapter<T, VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> {
    List<T> mData = new ArrayList<>();
    private boolean mCanLoop = false;

    public void setCanLoop(boolean canLoop) {
        mCanLoop = canLoop;
    }

    void setData(List<? extends T> data) {
        setData(data, false);
    }

    void setData(List<? extends T> data, boolean notify) {
        mData.clear();
        if (data != null) {
            mData.addAll(data);
        }

        if (notify) {
            notifyDataSetChanged();
        }
    }

    @Override
    final public void onBindViewHolder(VH holder, int position) {
        onBindItemViewHolder(holder, getRealPosition(position));
    }

    public abstract void onBindItemViewHolder(VH holder, int position);

    /**
     * 真实数据的大小
     */
    public int getRealItemCount() {
        return mData==null ? 0 : mData.size();
    }

    @Override
    public int getItemCount() {
        if(mCanLoop && getRealItemCount() > 1) {
            return Integer.MAX_VALUE;
        }

        return getRealItemCount();
    }

    public int getRealPosition(int position) {
        int realItemCount = getRealItemCount();
        if (realItemCount == 0) {
            return 0;
        }
        int realPosition = position % realItemCount;
        return realPosition;
    }

    public T getItemData(int position) {
        if(mData==null || mData.isEmpty()) {
            return null;
        }

        int realPosition = getRealPosition(position);
        return mData.get(realPosition);
    }
}
